package com.ruoyi.base.service.impl;

import java.util.List;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.base.mapper.BaseOrganizationMapper;
import com.ruoyi.base.domain.BaseOrganization;
import com.ruoyi.base.service.IBaseOrganizationService;

import javax.annotation.PostConstruct;
import javax.validation.Validator;

/**
 * 合作单位Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-12-20
 */
@Service
@Slf4j
public class BaseOrganizationServiceImpl implements IBaseOrganizationService 
{
    public static final String CACHE_MAP = "base_organization";
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private BaseOrganizationMapper baseOrganizationMapper;

    @Autowired
    protected Validator validator;

    @PostConstruct
    public int reCache(){
        redisCache.deleteObject(CACHE_MAP);
        return 0;
    }

    /**
     * 查询合作单位
     *
     * @param name 合作单位名称
     * @return 合作单位
     */
    @Override
    public BaseOrganization selectBaseOrganizationByName(String name){
        String key = "name_"+name;
        Long orgId = redisCache.getCacheMapValue(CACHE_MAP, name);
        if(orgId != null){
            return selectBaseOrganizationById(orgId);
        }

        BaseOrganization baseOrganization = baseOrganizationMapper.selectBaseOrganizationByName(name);
        if(baseOrganization != null){
            redisCache.setCacheMapValue(CACHE_MAP, key, baseOrganization.getId());
            redisCache.setCacheMapValue(CACHE_MAP, "id_"+baseOrganization.getId(), baseOrganization);
        }
        return baseOrganization;
    }

    /**
     * 查询合作单位
     * 
     * @param id 合作单位主键
     * @return 合作单位
     */
    @Override
    public BaseOrganization selectBaseOrganizationById(Long id)
    {
        String key = "id_"+id;
        BaseOrganization baseOrganization = redisCache.getCacheMapValue(CACHE_MAP, key);
        if(baseOrganization != null){
            return baseOrganization;
        }

        baseOrganization = baseOrganizationMapper.selectBaseOrganizationById(id);
        if(baseOrganization != null){
            redisCache.setCacheMapValue(CACHE_MAP, key, baseOrganization);
            redisCache.setCacheMapValue(CACHE_MAP, "name_"+baseOrganization.getName(), baseOrganization.getId());
        }
        return baseOrganization;
    }

    /**
     * 查询合作单位列表
     * 
     * @param baseOrganization 合作单位
     * @return 合作单位
     */
    @Override
    public List<BaseOrganization> selectBaseOrganizationList(BaseOrganization baseOrganization)
    {
        return baseOrganizationMapper.selectBaseOrganizationList(baseOrganization);
    }

    /**
     * 新增合作单位
     * 
     * @param baseOrganization 合作单位
     * @return 结果
     */
    @Override
    public int insertBaseOrganization(BaseOrganization baseOrganization)
    {
        BaseOrganization old = baseOrganizationMapper.selectBaseOrganizationByName(baseOrganization.getName());
        if(old != null){
            throw new ServiceException(baseOrganization.getName() + " 单位已存在");
        }
        baseOrganization.setCreateTime(DateUtils.getNowDate());
        return baseOrganizationMapper.insertBaseOrganization(baseOrganization);
    }

    /**
     * 修改合作单位
     * 
     * @param baseOrganization 合作单位
     * @return 结果
     */
    @Override
    public int updateBaseOrganization(BaseOrganization baseOrganization)
    {
        BaseOrganization old = baseOrganizationMapper.selectBaseOrganizationByName(baseOrganization.getName());
        if(old != null && !old.getId().equals(baseOrganization.getId())){
            throw new ServiceException(baseOrganization.getName() + " 单位已存在");
        }
        baseOrganization.setUpdateTime(DateUtils.getNowDate());
        return baseOrganizationMapper.updateBaseOrganization(baseOrganization) + reCache();
    }

    /**
     * 批量删除合作单位
     * 
     * @param ids 需要删除的合作单位主键
     * @return 结果
     */
    @Override
    public int deleteBaseOrganizationByIds(Long[] ids)
    {
        return baseOrganizationMapper.deleteBaseOrganizationByIds(ids) + reCache();
    }

    /**
     * 删除合作单位信息
     * 
     * @param id 合作单位主键
     * @return 结果
     */
    @Override
    public int deleteBaseOrganizationById(Long id)
    {
        return baseOrganizationMapper.deleteBaseOrganizationById(id) + reCache();
    }


    /**
     * 导入数据
     *
     * @param dataList 数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importData(List<BaseOrganization> dataList, Boolean isUpdateSupport, String operName){
        if (StringUtils.isNull(dataList) || dataList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (BaseOrganization row : dataList)
        {
            try
            {
                // 验证是否存在这个用户
                BaseOrganization old = baseOrganizationMapper.selectBaseOrganizationByName(row.getName());
                if (StringUtils.isNull(old))
                {
                    BeanValidators.validateWithException(validator, row);
                    row.setCreateBy(operName);
                    insertBaseOrganization(row);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、单位 " + row.getName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    BeanValidators.validateWithException(validator, row);
                    row.setId(old.getId());
                    row.setUpdateBy(operName);
                    updateBaseOrganization(row);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、单位 " + row.getName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、单位 " + row.getName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、单位 " + row.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        reCache();
        return successMsg.toString();
    }
}
